package crypto.symmetric;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

public class SymmetricTest {

	public byte[] encrypt(byte[] input) {
		byte[] output = null;
		// process..
		return output;
	}

	public byte[] decrypt(byte[] encryptedInput) {
		byte[] output = null;
		// process..
		return output;
	}

	public static void main(String[] args) {
		String input = "Wel";

		System.out.println("plain text: " + input);

		try {
			// Tao key
			KeyGenerator gen = KeyGenerator.getInstance("AES");
			SecureRandom sr = new SecureRandom();
			gen.init(sr);

			SecretKey key = gen.generateKey();
			final String tmpformat = key.getFormat();
			final byte[] tmpEndcoded = key.getEncoded();
			final String tmpAlgorithm = key.getAlgorithm();
			/*
			 * o day chung ta co the luu key nay vao Database de thuc hien cho
			 * viec view du lieu vao lan sau
			 */
			Key k = new Key() {

				@Override
				public String getFormat() {
					// TODO Auto-generated method stub
					return tmpformat;
				}

				@Override
				public byte[] getEncoded() {
					// TODO Auto-generated method stub
					byte[] a = { 124, 126, -96, -61, 88, -28, 29, 63, -87, -31,
							32, -61, -29, 119, -77, -91 };
					return tmpEndcoded;
				}

				@Override
				public String getAlgorithm() {
					// TODO Auto-generated method stub
					return tmpAlgorithm;
				}
			};
			// ma hoa
			Cipher cipher = Cipher.getInstance("AES");
			// cipher.init(Cipher.ENCRYPT_MODE, key);
			cipher.init(Cipher.ENCRYPT_MODE, k);
			byte[] encryptedOutput = cipher.doFinal(input.getBytes());

			System.out.println("encrypt text: " + new String(encryptedOutput));

			// giai ma
			cipher = Cipher.getInstance("AES");
			// cipher.init(Cipher.DECRYPT_MODE, key);
			cipher.init(Cipher.DECRYPT_MODE, k);
			byte[] decryptedOuput = cipher.doFinal(encryptedOutput);

			System.out
					.println("Decrypted Text : " + new String(decryptedOuput));

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
